package com.uiotsoft.small.app.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.app.entity.AppClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class AppBaseControl{
    protected AppClient appClient;

    public AppBaseControl(AppClient appClient) {
        this.appClient = appClient;
    }

    public boolean publishToHost(String model, String type, JSONObject data){
        String pubTopic = getATHTopic(model,type);
        String pubMsg = getSendData(data);
        return appClient.getMyMqttClient().appPublish(pubTopic,pubMsg);
    }

    public void publishToCloud(String model, String type, JSONObject data){
        String pubTopic = getATCTopic(model,type);
        String pubMsg = getSendData(data);
        appClient.getMyMqttClient().appPublish(pubTopic,pubMsg);
    }
    public String getSendData(JSONObject data){
        JSONObject sendData = new JSONObject();
        sendData.put("header",getHeader());
        sendData.put("payload",data);
        return sendData.toString();
    }
    public JSONObject getHeader(){
        String header = "{\"clientType\":\"uiot_app\",\"identity\":\"\",\"msgId\":\"\",\"appkey\":\"\",\"userUnique\":\"\",\"params\":{\"si\":\"\"},\"version\":\"1.0\",\"isEncrypt\":\"true\"}";
        JSONObject headerJson = JSONUtil.parseObj(header);
        headerJson.put("identity", appClient.getSi());
        headerJson.put("appkey", appClient.getAppKey());
        headerJson.put("userUnique", appClient.getUserUnique());
        JSONObject paramsJson = headerJson.getJSONObject("params");
        paramsJson.put("si",appClient.getSi());
        headerJson.put("params",paramsJson);
        long time = System.currentTimeMillis();
        headerJson.put("msgId",time+"");
        return headerJson;
    }

    public String getATCTopic(String model, String type){
        String tmp = "common/app/{}/{}/{}";
        return StrUtil.format(tmp,model,appClient.getSn(),type);
    }

    public String getATHTopic(String model, String type){
        String tmp = "host/app/{}/{}/{}";
        return StrUtil.format(tmp,model,appClient.getSn(),type);
    }
}
